import { SDKUserInfo } from "../Config/GlobalClass";
import { GlobalConfig } from "../Config/GlobalConfig";
import { GlobalEnum } from "../Config/GlobalEnum";
import { GlobalTmpData } from "../Config/GlobalTmpData";
import EventManager from "../Managers/EventManager";
import { EventTypes } from "../Managers/EventTypes";
import { AudioSystem } from "../SystemAudio/AudioSystem";
import { clog } from "../Tools/ColorLog";

export enum VideoState {
    unLoad = 0,
    loading = 1,
    success = 2,
    fail = 3,
}

export default class SDK {
    protected api = null;
    protected _sdkInfo: SDKUserInfo = new SDKUserInfo();
    protected _sysInfo: any = null;
    protected _userInfo: any = null;
    protected _city: string = null;

    protected _appid = 'shuduGame01';

    public init(callback?: Function, target?: any) {
        this.onEvents();
        this.initSdk(callback, target);

        GlobalConfig.isCloseVideo && console.warn('视频广告已关闭');
    }

    // 监听事件
    protected onEvents() {
        EventManager.on(EventTypes.SDKEvents.ShowBanner, this.showBanner, this);
        EventManager.on(EventTypes.SDKEvents.HideBanner, this.hideBanner, this);
        EventManager.on(EventTypes.SDKEvents.ShowVideo, this.showRewardedVideo, this);
        EventManager.on(EventTypes.SDKEvents.ShowInsertAd, this.showInterstitial, this);
        EventManager.on(EventTypes.SDKEvents.ShowCustomAd, this.showCustomAd, this);
        EventManager.on(EventTypes.SDKEvents.HideCustomAd, this.hideCustomAd, this);
        EventManager.on(EventTypes.SDKEvents.Share, this.share, this);
        EventManager.on(EventTypes.SDKEvents.ExitApp, this.onExitApp, this);

        //
        EventManager.on(EventTypes.SDKEvents.ShortVibration, this.onShortVibration, this);
        EventManager.on(EventTypes.SDKEvents.LongVibration, this.onLongVibration, this);

        // Log
        EventManager.on(EventTypes.SDKEvents.LoadFinish, this.onLoadFinish, this);
        EventManager.on(EventTypes.SDKEvents.GuideStep, this.onGuideStep, this);
        EventManager.on(EventTypes.SDKEvents.SkipGuide, this.onSkipGuide, this);
        EventManager.on(EventTypes.SDKEvents.FinishGuide, this.onFinishGuide, this);
        EventManager.on(EventTypes.SDKEvents.ShareReport, this.onShareReport, this);
        EventManager.on(EventTypes.SDKEvents.EnterStage, this.onEnterStage, this);
        EventManager.on(EventTypes.SDKEvents.ExitStage, this.onExitStage, this);
        EventManager.on(EventTypes.SDKEvents.ShowAdButton, this.onShowAdButton, this);
        EventManager.on(EventTypes.SDKEvents.ClickAd, this.onClickAd, this);
        EventManager.on(EventTypes.SDKEvents.ShowAd, this.onShowAd, this);
        EventManager.on(EventTypes.SDKEvents.CompleteAd, this.onCompleteAd, this);
        //-- 游戏功能
        EventManager.on(EventTypes.SDKEvents.FeedAnimal, this.onFeedAnimal, this);
        EventManager.on(EventTypes.SDKEvents.LvupSpd, this.onLvupSpd, this);


        //
        EventManager.on(EventTypes.SDKEvents.UpdateExptParams, this.onUpdateExptParams, this);

        // 授权
        EventManager.on(EventTypes.SDKEvents.CheckUserInfoAuth, this.onCheckUserInfoAuth, this);
        EventManager.on(EventTypes.SDKEvents.GetUserCity, this.onGetUserCity, this);
        EventManager.on(EventTypes.SDKEvents.GetUserInfo, this.onGetUserInfo, this);
        EventManager.on(EventTypes.SDKEvents.HideRankAuthBtn, this.onHideRankAuthBtn, this);
        //
        EventManager.on(EventTypes.SDKEvents.SetFeedbackBtn, this.onSetFeedbackBtn, this);


        // 好友排行
        EventManager.on(EventTypes.SDKEvents.GetFriendCloudStorage, this.onGetFriendCloudStorage, this);
        EventManager.on(EventTypes.SDKEvents.SetUserCloudStorage, this.onSetUserCloudStorage, this);

    }

    //#region ---对外接口
    public get appid() {
        return this._appid;
    }

    public get sysInfo() {
        if (!this._sysInfo && this.api) {
            this._sysInfo = this.api.getSystemInfoSync();
        }
        return this._sysInfo;
    }
    // 获取登陆信息
    public get loginResult() {
        if (!this.api) {
            console.log('# api is null');
            return null;
        }

        if (!this._loginResult) {
            this._loginResult = this.api['loginResult'];
        }
        return this._loginResult;
    }

    public get isAndroid(): boolean {
        return this.sysInfo &&
            this.sysInfo.platform.toLocaleLowerCase() === 'android';
    }

    public get isNewUser() {
        return this.loginResult && this.loginResult.newUser;
    }

    public get sdkInfo(): SDKUserInfo {
        if (this.loginResult) {
            this._sdkInfo.acount = this.loginResult.account;
            this._sdkInfo.isNewUser = this.isNewUser;
            this._sdkInfo.openid = this.loginResult.openid;
        }
        return this._sdkInfo;
    }

    public get userInfo() {
        return this._userInfo;
    }

    public get city() {
        return this._city;
    }

    //#endregion


    /**
    * 初始化SDK，操作所在SDK接口之前必须对SDK进行初始化 
    */
    protected setAdCfg() {

    }
    // ---------cxsdk
    // 登陆信息
    _loginResult: {
        account: string
        code: number
        message: string
        newUser: boolean
        openid: string
        os: string
        token: string
        uid: string
    } = null;
    protected qingjs = null;
    // 来源渠道
    protected channel = null;

    protected initSdk(callback?: Function, target?: any) {

        if (this.qingjs && this.qingjs.instance) {
            console.log('# SDK Init, qingjs ', this.qingjs);

            let _preTime = new Date().getTime();
            // 
            // 登录
            //
            this.qingjs.instance.login({}, (loginResult) => {
                // loginResult.code // 200 为成功，其他则失败
                // loginResult.uid // 用来标记唯一用户
                // loginResult.token // 用户token
                // loginResult.message // 登录结果描述

                let subTime = new Date().getTime() - _preTime;

                console.log("登录结束回调数据", loginResult, '耗时:', subTime, 'ms');

                // this.api['loginResult'] = loginResult;
                this._loginResult = loginResult;
                // 
                // 上报角色信息
                //
                this.qingjs.instance.reportRoleInfo({

                    roleId: loginResult.openid,            // string
                    roleName: loginResult.account,        // string
                    roleLevel: 100,                // int 角色等级
                    serverId: "0",          // string 区服ID需要唯一标识玩家所在区服，如果同时有区ID和服务器ID，请用竖线 “|” 连接起来
                    serverName: "0",        // string
                    roleVip: 8,                    // int 角色vip等级
                    rolePower: 99999,              // int 战力、武力之类角色的核心数值
                    roleGold: 100,                // int 次要货币(非氪金、游戏内可得货币)
                    roleDiamond: 100,             // int 主要货币(氪金获得)   
                    reportType: "entergame",   // string 上报类型 "entergame" , "createrole", "roleupgrade"

                }, function (result) {
                    console.log('上报角色信息完成:', result);
                });

                callback && callback();
            });

        } else {
            console.warn('# qingjs not found');
            callback && callback();
        }

        console.log('loginResult:', this.loginResult);
    }


    //#region ----------------功能---------
    //提示消息
    protected showMessage(msg: string) {
        EventManager.emit(EventTypes.GameEvents.ShowTips, msg);
    }
    // 短震动
    protected onShortVibration() {

    }
    // 长震动
    protected onLongVibration() {

    }

    //#endregion

    // #region -----------------事件---------------
    /**
       * 显示 Banner 广告
       */
    protected showBanner() {
        console.log("showBanner");
    }

    /**
     * 手动关闭 Banner 广告
     */
    protected hideBanner() {
        console.log("hideBanner");
    }

    /**
     * 拉起激励视频广告
     */
    protected showRewardedVideo(cb: Function | { success: Function, fail: Function, cancel: Function }, videoIdx: GlobalEnum.VideoIdx) {
        let success = null;
        let fail = null;
        let cancel = null;
        if (typeof cb === 'object') {
            success = cb.success;
            fail = cb.fail;
            cancel = cb.cancel;
        } else {
            success = cb;
        }
        //暂停游戏
        EventManager.emit(EventTypes.GameEvents.GamePause);
        AudioSystem.pauseBGM();
        //
        console.warn('观看视频中');
        // test Log
        this.onClickAd(GlobalEnum.VideoIdx[videoIdx], 'video');
        this.onShowAd(GlobalEnum.VideoIdx[videoIdx], 'video');

        setTimeout(() => {
            // test Log
            this.onCompleteAd(GlobalEnum.VideoIdx[videoIdx], 'video');
            //
            EventManager.emit(EventTypes.GameEvents.GameResume, 'video');
            AudioSystem.resumeBGM();
            success && success();
            this.onVideoComplete();
        }, 0);
    }
    /** 成功观看视频 */
    protected onVideoComplete(d?) {
        setTimeout(() => {
            EventManager.emit(EventTypes.SDKEvents.VideoComplete, d);
        }, 0);
    }
    private _isVideoTouchMask = false;
    private _touchMaskTimeoutId = 0;
    /** 视频广告点击之后屏蔽触摸-指定时间后自动恢复
     * @param hideTime 屏蔽触摸的时间(ms)
    */
    protected showVideoTouchMask(hideTime = 4000) {
        // 屏蔽触摸
        this._isVideoTouchMask = true;
        EventManager.emit(EventTypes.UIEvents.ShowTouchMask);

        // 设定延迟恢复
        clearTimeout(this._touchMaskTimeoutId);
        this._touchMaskTimeoutId = setTimeout(() => {
            clearTimeout(this._touchMaskTimeoutId);
            // 恢复触摸
            if (this._isVideoTouchMask) {
                this._isVideoTouchMask = false;
                EventManager.emit(EventTypes.UIEvents.HideTouchMask);
            }
        }, hideTime);
    }

    /**
     * 插屏广告
     */
    protected showInterstitial(cb1?, cb2?) {
        console.log("showInterstitial");
        cb1 && cb1();

    }

    /**
     * 显示原生模板广告
     */
    protected showCustomAd(adIndex: number) {
        console.log("showCustomAd");

    }

    /**
     * 手动关闭原生模板广告
     */
    protected hideCustomAd(adIndex: number) {
        console.log("hideCustomAd");

    }

    /**
     * 自定义分享
     */
    protected share(msg?) {
        console.log("share");

        this.onShareComplete();
    }
    // 分享完成
    protected onShareComplete(d?) {
        setTimeout(() => {
            EventManager.emit(EventTypes.SDKEvents.ShareComplete, d);
        }, 0);
    }
    // #endregion

    //退出游戏
    protected onExitApp() {

    }

    //#region --- 个人信息

    // 获取城市
    protected onGetUserCity(cb?) {

    }
    // 检测是否授权
    protected onCheckUserInfoAuth(cb?) {

    }
    // 隐藏授权按钮
    protected onHideRankAuthBtn() {

    }
    // 获取用户信息
    protected onGetUserInfo(cb?) {

    }
    // 设置反馈按钮
    protected onSetFeedbackBtn(isShow = false) {

    }
    //#endregion

    //#region ---排行榜
    protected _rankInfo: GlobalEnum.RankInfo = new GlobalEnum.RankInfo();
    // 保存自身排行数据-好友排行
    protected onSetUserCloudStorage(key: string, value: number) {

    }
    // 获取好友排行
    protected onGetFriendCloudStorage(key_v: string, callback?: Function, userInfo?: any) {

    }

    //#endregion


    //#region --- 上报日志
    onLoadFinish(d?) {
        this.onReportEvent('onLoadFinish', d);
    }
    onFinishGuide(d?) {
        this.onReportEvent('onFinishGuide', d);
    }
    // 引导步骤
    onGuideStep(step: number) {
        this.onReportEvent('onGuideStep', step);
    }
    // 退出引导
    onSkipGuide(step: number) {
        this.onReportEvent('onSkipGuide', step);
    }

    onShareReport(d?) {
        this.onReportEvent('onShareReport', d);
    }

    onReportEvent(key: string, data = {}) {
        console.log('上报事件：' + key, data);
    }
    // 当前关卡
    _getCurLvMsg() {
        return '关卡' + GlobalTmpData.CurLv + '';
    }
    // 当前关卡类型
    _getCurLvType() {
        let msg = '';
        if (GlobalTmpData.Game.isGuideLv) {
            msg = '练习';
        } else {
            if (GlobalTmpData.isHardMode) {
                msg = '挑战';
            } else {
                msg = '普通';
            }
        }
        return msg;
    }

    // 进入关卡
    onEnterStage() {
        let msg = this._getCurLvType() + this._getCurLvMsg();
        console.log('# LOG: 进入关卡', 'Level: ' + msg);
    }
    exitStates = ['胜利', '失败', '中途退出'];
    // 退出关卡
    onExitStage(state = 0) {
        let lv = this._getCurLvType() + this._getCurLvMsg();
        let msg = lv + ' -> ' + this.exitStates[state];

        console.log('# LOG: 退出关卡', 'Level: ' + msg);
    }
    // 显示广告按钮
    onShowAdButton(ui, adType: string) {
        console.log('# LOG: 显示广告按钮', 'UI: ' + GlobalEnum.VideoIdx[ui]);
    }
    // 点击广告
    onClickAd(ui, adType: string) {
        console.log('# LOG: 点击广告', 'UI: ' + ui);

    }
    // 展示广告
    onShowAd(ui, adType: string, d?) {
        console.log('# LOG: 展示广告', 'UI: ' + ui);

    }
    // 完整观看广告
    onCompleteAd(ui, adType: string, d?) {
        console.log('# LOG: 完整观看广告', 'UI: ' + ui);

    }
    // 喂养动物
    onFeedAnimal(d?) {
        console.log('# LOG: 喂养动物', d);
    }
    // 点击升级
    onLvupSpd(d?) {
        console.log('# LOG: 点击升级', d);
    }

    //#endregion


    //#region --- 更新实验参数
    onUpdateExptParams() {

    }

    //#endregion

}
